import json

from common.openai_ali import get_client


def completion(messages:list):
    client = get_client()
    completion = client.chat.completions.create(
        model="qwen-plus",  # 指定模型
        messages=messages,
        stream=False  # 非流式输出
    )
    msg = completion.choices[0].message
    return {"role":msg.role, "content":msg.content}

def completion_all(messages:list):
    client = get_client()
    completion = client.chat.completions.create(
        model="qwen-plus",  # 指定模型
        messages=messages,
        stream=False  # 非流式输出
    )
    msg = completion.choices[0].message
    return msg

def completion_tools(messages:list,tools:list):
    client = get_client()
    completion = client.chat.completions.create(
        model="qwen-plus",  # 指定模型
        messages=messages,
        tools=tools,
        tool_choice={
            "type": "function",
            "function": {"name": "add_to_cart"}  # 强制调用这个函数
        }
    )
    msg = completion.choices[0].message
    idx = 0
    if msg.tool_calls:
        for tc in msg.tool_calls:
            fun_name = tc.function.name
            fun_args = tc.function.args
            js = json.loads(tc.function.arguments)

            idx += 1

    return msg